package com.celi.scs.system.controller;

import cn.hutool.core.util.IdUtil;
import com.celi.cii.base.ResponseDTO;
import com.celi.scs.common.constant.NumberConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("${url.prefix}/file")
public class FileController {

    @Value("${cii.file.upload}")
    private String remoteDirectory;

    @PostMapping(value = "/upload")
    public ResponseDTO<String> uploadFileOss(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String saveFileName = IdUtil.simpleUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + NumberConstant.Number_1);
        File directory = new File(remoteDirectory);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File dest = new File(remoteDirectory + File.separator + saveFileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseDTO.ok(saveFileName);
    }

    /**
     * 下载文件
     *
     */
    @GetMapping(value = "/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filename) {
        try {
            Path filePath = Paths.get(remoteDirectory).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

}

